import { operationToColor } from "../utils/help";

const upColor = '#ec0000';
const upBorderColor = '#8A0000';
const downColor = '#00da3c';
const downBorderColor = '#008F28';

// Each item: open，close，lowest，highest
let data0 = splitData([
    ['2013/1/24', 2320.26, 2320.26, 2287.3, 2362.94],
    ['2013/1/25', 2300, 2291.3, 2288.26, 2308.38],
    ['2013/1/28', 2295.35, 2346.5, 2295.35, 2346.92],
    ['2013/1/29', 2347.22, 2358.98, 2337.35, 2363.8],
    ['2013/1/30', 2360.75, 2382.48, 2347.89, 2383.76],
    ['2013/1/31', 2383.43, 2385.42, 2371.23, 2391.82],
    ['2013/2/1', 2377.41, 2419.02, 2369.57, 2421.15],
]);

let volume = []
let gdates = []

function splitData(rawData) {
    const categoryData = [];
    const values = [];
    for (var i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
    }

    return {
        categoryData: categoryData,
        values: values
    };
}

function calculateMA(dayCount) {
    var result = [];
    for (var i = 0, len = data0.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += +data0.values[i - j][1];
        }
        result.push(sum / dayCount);
    }
    return result;
}

function getOption(stock) {
    let option = {
        title: {
            text: stock,
            left: 0
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return params[0].name + '<br/>' +
                    //params[0].seriesName + ' : ' + params[0].data[5]
                    'close : ' + params[0].data[2]  + '<br/>' +
                    'pct : ' + params[0].data[5]  + '<br/>' +
                    'lp : ' + params[0].data[6]
            }
            /*
            axisPointer: {
                type: 'cross'
            }
                */
        },
        legend: {
            data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30','MA60','MA100','MA200','MA300'],
            selected: {
                '日K': true,
                'MA5': false,
                'MA10': false,
                'MA20': true,
                'MA30': false,
                'MA60': true,
                'MA100': true,
                'MA200': false,
                'MA300': true
            }
        },
        visualMap: {
            show: false,
            seriesIndex: 5,
            dimension: 2,
            pieces: [
              {
                value: 1,
                color: downColor
              },
              {
                value: -1,
                color: upColor
              }
            ]
          },
        grid: [
            {
                left: '10%',
                right: '8%',
                height: '50%'
            },
            {
                left: '10%',
                right: '8%',
                top: '63%',
                height: '16%'
            }
        ],
        xAxis: [{
            type: 'category',
            data: data0.categoryData,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            axisPointer: {
                z: 100
            },
            min: 'dataMin',
            max: 'dataMax'
        },
        {
            type: 'category',
            gridIndex: 1,
            data: data0.categoryData,
            boundaryGap: false,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            min: 'dataMin',
            max: 'dataMax'
        }],
        yAxis: [{
            scale: true,
            splitArea: {
                show: true
            }
        },
        {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLabel: { show: false },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false }
        }],
        dataZoom: [
            {
              type: 'inside',
              xAxisIndex: [0, 1],
              start: 82,
              end: 100
            },
            {
              show: true,
              xAxisIndex: [0, 1],
              type: 'slider',
              top: '85%',
              start: 82,
              end: 100
            }
          ],
    series: [
        {
            name: '日K',
            type: 'candlestick',
            data: data0.values,
            itemStyle: {
                color: upColor,
                color0: downColor,
                borderColor: upBorderColor,
                borderColor0: downBorderColor
            },
            markArea: getMarkAreaDate(gdates),
            markPoint: {
                tooltip: {
                    formatter: function (param) {
                        return param.name + '<br>' + (param.data.coord || '');
                    }
                }
            },
            markLine: {
                symbol: ['none', 'none'],
                data: [
                    [
                        {
                            name: 'from lowest to highest',
                            type: 'min',
                            valueDim: 'lowest',
                            symbol: 'circle',
                            symbolSize: 10,
                            label: {
                                show: false
                            },
                            emphasis: {
                                label: {
                                    show: false
                                }
                            }
                        },
                        {
                            type: 'max',
                            valueDim: 'highest',
                            symbol: 'circle',
                            symbolSize: 10,
                            label: {
                                show: false
                            },
                            emphasis: {
                                label: {
                                    show: false
                                }
                            }
                        }
                    ],
                    {
                        name: 'min line on close',
                        type: 'min',
                        valueDim: 'close'
                    },
                    {
                        name: 'max line on close',
                        type: 'max',
                        valueDim: 'close'
                    }
                ]
            }
        },
        {
            name: 'MA5',
            type: 'line',
            data: calculateMA(5),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'MA10',
            type: 'line',
            data: calculateMA(10),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'MA20',
            type: 'line',
            data: calculateMA(20),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'MA30',
            type: 'line',
            data: calculateMA(30),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'MA60',
            type: 'line',
            data: calculateMA(60),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'MA100',
            type: 'line',
            data: calculateMA(100),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'MA200',
            type: 'line',
            data: calculateMA(200),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'MA300',
            type: 'line',
            data: calculateMA(300),
            smooth: true,
            lineStyle: {
                opacity: 0.5
            }
        },
        {
            name: 'Volume',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            smooth: true,
            data: getVolume() 
        }
    ]
};
    return option;
}

function getVolume() {
    return volume;
}

function builtMarkItem(name, element, type = 1 ,color = '') {
    return {
        name: name,
        value: type == 1 ? name : element.pct,
        xAxis: element.date,
        yAxis: element.close,
        itemStyle: {
            color: color || operationToColor(name)
        }
    }
}

function builtMarkPoint(data, pctMark = '', opShow = true) {

    let ret = []
    if (opShow) {
        data.forEach(element => {
            if (element.operation !== null) {
                element.operation.forEach(i => {
                    if (["买入", "卖出", "分红", "模拟买入", "模拟卖出"].includes(i.operation)) {
                        ret.push(builtMarkItem(i.operation, element));
                    }
                })
            }
        });
    }
    if (pctMark !== '') {
        let op = pctMark.split(';')[0]
        let v = pctMark.split(';')[1]
        data.forEach(element => {
            if (op == 'gt') {
                if (element.pct >= v) {
                    ret.push(builtMarkItem(pctMark, element,2, "rgba(249, 175, 175, 1)"))
                }
            } else {
                if (element.pct <= v * -1) {
                    ret.push(builtMarkItem(pctMark, element,2 ,"rgba(3, 85, 3, 1)"))
                }
            }
        })
    }
    return ret
}

function getMarkPointData(rawData, pctMark = '', opShow = true) { 
    return [
        {
            name: 'highest value',
            type: 'max',
            valueDim: 'highest'
        },
        {
            name: 'lowest value',
            type: 'min',
            valueDim: 'lowest'
        },
        {
            name: 'average value on close',
            type: 'average',
            valueDim: 'close'
        }
    ].concat(builtMarkPoint(rawData, pctMark, opShow));
}

function rebuiltDataOAndVolume(rawData) {

    gdates = []
    volume = []

    let data = []

    rawData.forEach(function (item, i) {

        gdates.push(item["date"])

        let raw = [];
        raw.push(item["date"])
        // Each item: open，close，lowest，highest
        raw.push(item["open"])
        raw.push(item["close"])
        raw.push(item["low"])
        raw.push(item["high"])
        raw.push(item["pct"])
        raw.push(item["lp"])

        volume.push([item["date"], item['volume'], item['close'] > item['open'] ? 1 : -1]);

        data.push(raw)
    });

    data0 = splitData(data)
}

export function builtData(stock, rawData, pctMark = '', opShow = true) {
    rebuiltDataOAndVolume(rawData)
    let options = getOption(stock)

    let markPointData = getMarkPointData(rawData, pctMark, opShow)
    options.series[0].markPoint.data = markPointData

    return options
}

function buildMarkAreaDate(dates) {
  let grouped = dates.reduce((map, item) => {
  let key = item.slice(0, 7);
  const group = map.get(key) || [];
  group.push(item);
  return map.set(key, group);
  }, new Map());

  let ret = []
  grouped.forEach((value, key) => {
    if(key.slice(-1) % 2 === 0) {
        let item = [{
          name: key,
          xAxis: value[0],
        },
        {
          xAxis: value[value.length - 1],
        }]

      ret.push(item)
    }
  });
  return ret
}

function getMarkAreaDate(dates) {
  return {
    itemStyle: {
      color: 'rgba(255, 173, 177, 0.4)'
    },
    data: buildMarkAreaDate(dates)
  }
}